package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/3/18 09:30
 */
public class Dws_03_DwsTrafficPageViewWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_03_DwsTrafficPageViewWindow().init(
            4003,
            2,
            "Dws_03_DwsTrafficPageViewWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 过滤出首页和详情页数据
        SingleOutputStreamOperator<JSONObject> homeAndGoodDetailStream = filterHomeAndGoodDetail(stream);
        
        // 2. 把数据封装到 pojo 中
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = parseToPojo(homeAndGoodDetailStream);
        
        // 3. 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream = windowAndAgg(beanStream);
    
        // 4. 写出到 clickhouse
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_page_view_window", TrafficHomeDetailPageViewBean.class));
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream) {
        return beanStream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1,
                                                                TrafficHomeDetailPageViewBean value2) throws Exception {
                        value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                        value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                        return value1;
                    }
                },
                new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<TrafficHomeDetailPageViewBean> elements,
                                        Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TrafficHomeDetailPageViewBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                    
                        bean.setTs(System.currentTimeMillis());
                    
                        out.collect(bean);
                    }
                }
            );
           
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> parseToPojo(
        SingleOutputStreamOperator<JSONObject> homeAndGoodDetailStream) {
        return homeAndGoodDetailStream
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
                
                private ValueState<String> lastVisitHomeDateState;
                private ValueState<String> lastVisitGoodDetailDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastVisitHomeDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastVisitHomeDate", String.class));
                    lastVisitGoodDetailDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastVisitGoodDetailDate", String.class));
                }
                
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                    Long ts = value.getLong("ts");
                    String pageId = value.getJSONObject("page").getString("page_id");
                    
                    String today = AtguiguUtil.tsToDate(ts);
                    
                    Long homeUvCt = 0L;
                    // 是否是今天第一个 home
                    String lastVisitHomeDate = lastVisitHomeDateState.value();
                    if ("home".equals(pageId) && !today.equals(lastVisitHomeDate)) {
                        homeUvCt = 1L;
                        lastVisitHomeDateState.update(today);
                    }
                    
                    Long goodDetailUvCt = 0L;
                    String lastVisitGoodDetailDate = lastVisitGoodDetailDateState.value();
                    if ("good_detail".equals(pageId) && !today.equals(lastVisitGoodDetailDate)) {
                        goodDetailUvCt = 1L;
                        lastVisitGoodDetailDateState.update(today);
                    }
                    
                    if (homeUvCt + goodDetailUvCt > 0) {
                        out.collect(new TrafficHomeDetailPageViewBean("", "",
                                                                      homeUvCt, goodDetailUvCt,
                                                                      ts
                        ));
                    }
                    
                    
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> filterHomeAndGoodDetail(DataStreamSource<String> stream) {
        // 由于数据过滤之后,会变少, 甚至有可能数据倾斜. 为了防止水印的更新问题: 在过滤前定义水印
        return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
                    .withIdleness(Duration.ofSeconds(60))
            )
            .filter(new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject obj) throws Exception {
                    String pageId = obj.getJSONObject("page").getString("page_id");
                    return "home".equals(pageId) || "good_detail".equals(pageId);
                }
            });
        
        
    }
}
/*
流量域页面浏览各窗口汇总

统计当日的首页和商品详情页独立访客数。

1. 数据源: 页面日志

2. 只过滤出首页和商品详情页

3. 分别计算首页和商品详情页的独立访客数
    keyBy: mid
    
    两个状态:
        首页
        商品详情页
        
 4. 开窗聚合
     要不要 keyBy: 不用
     
     窗口: windowAll
        窗口的处理函数的并行度只能是 1
        
 5. 写出到 clickhouse
 
 




 */
